# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
from odoo.exceptions import UserError, ValidationError


import logging
_logger = logging.getLogger(__name__)



class HrExpense(models.Model):
    _inherit = "hr.expense"
    check_department_id = fields.Many2one('hr.department', string='Check Department', related='sheet_id.check_department_id' )
    check_rule_id = fields.Many2one('hr.check.rule', string='Check Rule', related='check_department_id.check_rule_id' )
    check_rule_line_id = fields.Many2one('hr.check.rule.line', string='Check Rule Lines', compute='_compute_rule' )
    is_over_range = fields.Boolean(string='Check Rule Lines', compute='_compute_rule' )
    
    @api.depends('sheet_id', 'check_department_id', 'check_rule_id')
    def _compute_rule(self):
        rule_line = self.check_rule_id.line_ids.filtered(lambda rule: rule.product_id == self.product_id )
        
        is_over_range = False
        
        if rule_line:
            rl = rule_line[0]
            self.check_rule_line_id = rl
            
            if rl.check_type == 'price':
                val = self.unit_amount  
            else:
                val = self.total_amount
            
            is_over_range = not ( val >= rl.min_amount and val < rl.max_amount )
            
        self.is_over_range = is_over_range


class HrExpenseSheet(models.Model):
    _inherit = "hr.expense.sheet"

    check_department_id = fields.Many2one('hr.department', string='Check Department', states={'post': [('readonly', True)], 'done': [('readonly', True)]})

    @api.multi
    def next_check(self, check_department_id ):
        self.ensure_one()
        self.check_department_id = check_department_id


    @api.multi
    def _check_over_range(self):
        for line in self.expense_line_ids:
            if line.is_over_range:
                return True
                
        return False


    @api.multi
    def approve_expense_sheets(self):
        if self._check_over_range():
            raise UserError(_("当前费用单超过了你的审批权限，请提交上级部门经理审批"))
        
        #else:
        #    raise UserError(_("ok you 审批"))
        
        return super(HrExpenseSheet, self).approve_expense_sheets()


class HrCheckRule(models.Model):

    _name = "hr.check.rule"
    _description = "Check Rule"
    _order = "id"
    
    name = fields.Char('Description')
    line_ids = fields.One2many('hr.check.rule.line', 'rule_id', string='Check Rule Lines' )


class HrCheckRuleLine(models.Model):

    _name = "hr.check.rule.line"
    _description = "Check Rule"
    _order = "id"
    
    name = fields.Char('Description')
    rule_id = fields.Many2one('hr.check.rule', string='Check Rule', required=True)

    product_id = fields.Many2one('product.product', string='Product', required=True)

    check_type = fields.Selection([
        ('price', 'Price'),
        ('total', 'Total Amount'),
    ], string='Check Type', default= 'total' )

    min_amount = fields.Float("Min Amount", required=True,  digits=dp.get_precision('Product Price'))
    max_amount = fields.Float("Max Amount", required=True,  digits=dp.get_precision('Product Price'))

class HrDepartment(models.Model):
    _inherit = 'hr.department'

    check_rule_id = fields.Many2one('hr.check.rule', string='Check Rule' )


